package com.hankol.feature_wine_meal.viewmodel

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Point
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.lifecycle.MutableLiveData
import com.baselibrary.Constants
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.CommentEnum
import com.baselibrary.bean.ShareItemBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.LoadingManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.view.share.SharePopupWindow
import com.okhttp.comment.CommentBean
import com.baselibrary.activity.BaseActivity
import com.baselibrary.utils.ShareManager
import com.hankol.feature_wine_meal.WineMealPosterActivity
import com.hankol.feature_wine_meal.api.OnUpPosterCallBack
import com.hankol.feature_wine_meal.api.WineMealHelp
import com.hankol.feature_wine_meal.bean.FoodDetailsBean
import com.hankol.feature_wine_meal.bean.foodBean2SelectSendFriend2Bean
import com.hankol.feature_wine_meal.bean.showShare2Bean2SelectSendFriend2Bean
import com.hankol.feature_wine_meal.databinding.ActivityWineMealDetaBinding
import com.hankol.feature_wine_meal.databinding.ActivityWineMealPosterBinding
import com.hankol.feature_wine_meal.respository.WineMealRequestManager
import com.transitionseverywhere.TransitionManager
import com.zxing.ZxingManager
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.util.*
import kotlin.math.roundToInt

/**
 * @author: 关忆北、
 * @date: 2022/6/28
 * @Des：
 */
class WineMealViewModel : BaseViewModel() {
    val foodInfoLD: MutableLiveData<FoodDetailsBean> = MutableLiveData()
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()//评论列表
    var upCollectionTime: Long = 0

    fun reqFoodInfo(id: Long) {
        WineMealRequestManager.getInstance().reqFoodInfo(id, foodInfoLD)
    }

    //评论
    fun reqCommentList(page: Int, commentEnum: CommentEnum, typeId: Long, topCommentId: Long) {
        WineMealRequestManager.getInstance().reqCommentList(commentListLiveData, commentEnum.commentType, page, typeId, 0, topCommentId)
    }

    //评论
    fun reqCommentList(page: Int, commentEnum: CommentEnum, typeId: Long, topCommentId: Long, pId: Long) {
        WineMealRequestManager.getInstance().reqCommentList(commentListLiveData, commentEnum.commentType, page, typeId, pId, topCommentId)
    }

    fun showShare(detailsBean: FoodDetailsBean, activity: BaseActivity, wineMealHelp: WineMealHelp): SharePopupWindow? {
        val title = if (detailsBean.name.checkNotNull()) detailsBean.name else "这是一个下酒菜"
        val des = if (detailsBean.desc.checkNotNull()) detailsBean.desc else ""
        val shareItem = ShareManager.showSharePopWindow(activity, wineMealHelp.getShareUrl() + detailsBean.id, detailsBean.cover, title, des, object : SharePopupWindow.OnShareClickListener {

            override fun onShareClick(type: Int) {
                when (type) {
                    ShareItemBean.DOWN -> {

                    }
                    ShareItemBean.POSTER -> {
                        PermissionsUtils.getInstance().chekPermissions(activity, PermissionCollection.FILE.permissionList, object : PermissionsCall() {
                            override fun permissionsPass() {
                                val bundle = Bundle()
                                bundle.putString(WineMealPosterActivity.WINE_MEA_NAME, title)
                                bundle.putString(WineMealPosterActivity.WINE_MEA_DES, des)
                                bundle.putString(WineMealPosterActivity.WINE_MEA_COVER, detailsBean.cover)
                                bundle.putLong(WineMealPosterActivity.WINE_MEA_ID, detailsBean.id)
                                bundle.putString(WineMealPosterActivity.WINE_MEA_AUTHOR_NAME, detailsBean.authorName)
                                bundle.putString(WineMealPosterActivity.WINE_MEA_AUTHOR_HEAD, detailsBean.authorIcon)
                                ARouterUtils.jump(ActivityRouter.WINE_MEAL.WINE_MEAL_POSTER, bundle)
                            }
                        })
                    }
                    ShareItemBean.REPORT -> {
                        /* val juBaoIntent = Intent(activity, JuBaoOneActivity::class.java)
                         val bundle = Bundle()
                         bundle.putInt("type", 2)
                         bundle.putInt("id", commContentBean.getId())
                         bundle.putInt("complaintUserId", commContentBean.getUser().getId())
                         juBaoIntent.putExtras(bundle)
                         startActivity(juBaoIntent)*/

                    }
                }
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {//私信
                    val foodBean2SelectSendFriend2Bean = foodBean2SelectSendFriend2Bean(detailsBean)
                    wineMealHelp.startShareFriend(activity, bean.userId, bean, foodBean2SelectSendFriend2Bean)
                } else {
                    val showShare2Bean2SelectSendFriend2Bean = showShare2Bean2SelectSendFriend2Bean(detailsBean)
                    wineMealHelp.startShareFriend(activity, bean.userId, bean, showShare2Bean2SelectSendFriend2Bean)
                }

            }
        })
        shareItem?.setShareItem(true, false, false);
        return shareItem
    }

    /**
     * 更新点赞状态
     */
    fun upSupportSate(dataBinding: ActivityWineMealDetaBinding, detailsBean: FoodDetailsBean) {
        if (dataBinding.includeWineComment.llCommentGive.isSelected) {
            //执行取消点赞
            detailsBean.hasLiked = 0
            detailsBean.supportNum = detailsBean.supportNum.minus(1)
            if (detailsBean.supportNum < 0) detailsBean.supportNum = 0
        } else {
            //执行点赞动作
            detailsBean.hasLiked = 1
            detailsBean.supportNum = detailsBean.supportNum.plus(1)
        }
        dataBinding.includeWineComment.ivCommentGiveState.isLiked = detailsBean.hasLiked == 1
        dataBinding.includeWineComment.llCommentGive.isSelected = detailsBean.hasLiked == 1
        dataBinding.includeWineComment.tvCommentGiveCount.text = if (detailsBean.supportNum <= 0) "点赞" else NumberUtils.formatBigNum(detailsBean.supportNum.toString())
    }

    /**
     * 更新收藏状态
     */
    fun upCollectionSate(dataBinding: ActivityWineMealDetaBinding, detailsBean: FoodDetailsBean) {

        if (dataBinding.includeWineComment.llCommentCollection.isSelected) {
            //取消收藏
            detailsBean.hasFavorite = 0
            detailsBean.favoriteNum = detailsBean.favoriteNum.minus(1)

        } else {
            //收藏
            detailsBean.hasFavorite = 1
            upCollectionTime = System.currentTimeMillis()//更新收藏时间
            detailsBean.favoriteNum = detailsBean.favoriteNum.plus(1)
        }
        dataBinding.includeWineComment.ivCommentConState.isLiked = detailsBean.hasFavorite == 1
        dataBinding.includeWineComment.llCommentCollection.isSelected = detailsBean.hasFavorite == 1
        dataBinding.includeWineComment.tvCommentConCount.text = if (detailsBean.favoriteNum <= 0) "收藏" else NumberUtils.formatBigNum(detailsBean.favoriteNum.toString())
    }

    fun upPosterView(dataBinding: ActivityWineMealPosterBinding, fatherViewWidth: Int, sonViewWidth: Int) {
        TransitionManager.beginDelayedTransition(dataBinding.llWineMealPoster)
        val fatherParams: RelativeLayout.LayoutParams = dataBinding.rlWinePosterSon.layoutParams as RelativeLayout.LayoutParams
        val sonParams: LinearLayout.LayoutParams = dataBinding.roundCover.layoutParams as LinearLayout.LayoutParams

        fatherParams.width = fatherViewWidth
        sonParams.width = sonViewWidth

        fatherParams.height = (fatherViewWidth / WineMealPosterActivity.WINE_MEA_POSTER_FATHER).roundToInt()
        sonParams.height = (sonViewWidth / WineMealPosterActivity.WINE_MEA_POSTER_SON).roundToInt()

        dataBinding.rlWinePosterSon.layoutParams = fatherParams
        dataBinding.roundCover.layoutParams = sonParams

    }


    fun createHaiBao(activity: Activity, dataBinding: ActivityWineMealPosterBinding, callback: OnUpPosterCallBack) {
        LoadingManager.showLoadingDialog(activity)
        try {
            runBlocking {
                val HBCtrip = GlobalScope.async {
                    val bitmap = BitmapUtils.convertViewToBitmap(dataBinding.rlWinePoster);
                    val createPosterFile = FileUtils.createPosterFile()
                    FileUtils.compressBmpToFile4Fixed(bitmap, createPosterFile, 50)
                    callback.onSuccess("", createPosterFile.absolutePath.checkValue())
                    LoadingManager.hideLoadingDialog(activity)

                }
            }
        } catch (e: Exception) {
            LoadingManager.hideLoadingDialog(activity)
            ToastUtils.showShort(activity.applicationContext, "网络异常，请稍后再试")
            e.message
        }
    }


    /**
     * 获取图片URL地址
     *
     * @param imageUrl
     */
    private fun upLoadImages(activity: Activity, filePath: String, callback: OnUpPosterCallBack) {
        callback.onSuccess("", filePath)
        LoadingManager.hideLoadingDialog(activity)
    }

    /**
     * 判断当前view是否在屏幕可见
     */
    fun getLocalVisibleRect(activity: Activity, view: View, offsetY: Int): Boolean {
        val p = Point()
        activity.windowManager.defaultDisplay.getSize(p)
        val screenWidth: Int = p.x
        val screenHeight: Int = p.y
        val rect = Rect(0, 0, screenWidth, screenHeight)
        val location = IntArray(2)
        location[1] = location[1] + ScreenUtils.dpToPx(offsetY)
        view.getLocationInWindow(location)
        view.tag = location[1] //存储y方向的位置
        return view.getLocalVisibleRect(rect)
    }

    /**
     * 查看大图
     */
    fun browseImg(mImgList: ArrayList<String>, position: Int) {
        val bundle = Bundle()
        val imgList: ArrayList<String> = ArrayList(mImgList)
        bundle.putStringArrayList(Constants.WIKI_PICTURE_LIST, imgList)
        bundle.putInt(Constants.WIKI_PICTURE_INDEX, position)
        bundle.putString(Constants.WIKI_PICTURE_WATERMARK, Constants.WIKI_PICTURE_WATERMARK)
        ActivityRouter.startActivity(ActivityRouter.ACTIVITY.BROWSE_MEDIA, bundle)
    }

    /**
     * 生成二维码
     *
     * @param name
     */
    open fun createQRCode(context: Context, name: String): Bitmap {
        return ZxingManager.getInstance(context).createQRCode(name)
    }
}